package com.markedquilt.home.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ZhangKe
 * @Description 在过滤器中存储客户端发起请求的时间戳
 * @date 2020/12/27 0:00.
 */
@Slf4j
@Component
public class AccessLogFilter extends ZuulFilter {
    /**
     * 制定过滤器类型
     * @return 类型String,客户端发起请求之前
     */
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    /**
     * 过滤器执行顺序，优先级，越小，优先级越高
     * 比最后一个Filter优先级高一点点
     * @return
     */
    @Override
    public int filterOrder() {
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 1;
    }

    /**
     * 是否启动当前过滤器
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // RequestContext 用于在过滤器之间传递消息
        RequestContext ctx = RequestContext.getCurrentContext();
        Long startTime = (Long) ctx.get("startTime");

        HttpServletRequest request = ctx.getRequest();
        String uri = request.getRequestURI();

        long duration = System.currentTimeMillis() - startTime;
        log.info("uri:{}, duration:{} ms",uri,duration/100);
        return null;
    }
}
